package com.fc.advbox.service.impl;

import com.fc.advbox.dao.InvestorAcctDao;
import com.fc.advbox.dao.InvestorAcctTxnDao;
import com.fc.advbox.dao.InvestorAssetDao;
import com.fc.advbox.entity.InvestorAcctTxnEntity;
import com.fc.advbox.entity.InvestorAssetEntity;
import com.fc.advbox.service.IInvestorAssetService;
import com.fc.advbox.utils.Constant;
import com.fc.advbox.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Description:
 * User: Charles.Gao
 * Date: 2018-07-09 16:10
 */
@Service
public class InvestorAssetServiceImpl implements IInvestorAssetService {
    @Autowired
    private InvestorAssetDao investorAssetDao;

    @Autowired
    private InvestorAcctDao investorAcctDao;

    @Autowired
    private InvestorAcctTxnDao investorAcctTxnDao;

    @Override
    public List<InvestorAssetEntity> queryList(Map<String, Object> params) {
        return investorAssetDao.queryList(params);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return investorAssetDao.queryTotal(map);
    }

    @Override
    public int queryTotal(Query query) {
        return investorAssetDao.queryTotal(query);
    }

    @Override
    public InvestorAssetEntity queryObject(Long id) {
        return investorAssetDao.queryObject(id);
    }

    @Override
    @Transactional
    public void save(InvestorAssetEntity asset){
        investorAssetDao.save(asset);
        investorAcctDao.changeAmt(asset.getUserId(),asset.getAmount().doubleValue());
        InvestorAcctTxnEntity t = new InvestorAcctTxnEntity();
        t.setAssetId(asset.getId());
        t.setTxnType(Constant.AcctTxnType.BUY.getValue());
        t.setReciprocalAccount("System");
        t.setCreateTime(new Date());
        t.setAmount(asset.getAmount());
        //TODO t.setBalance();
        t.setAcctId(asset.getAcctId());
        t.setReciprocalName("System");
        investorAcctTxnDao.save(t);
    }

    @Override
    public void update(InvestorAssetEntity asset){
        InvestorAssetEntity  assetBefore = investorAssetDao.queryObject(asset.getId());
        double amtChange = assetBefore.getAmount().doubleValue() - asset.getAmount().doubleValue();
        investorAssetDao.update(asset);
        investorAcctDao.changeAmt(asset.getUserId(),0-amtChange);
    }

    @Override
    public void delete(Long id) {
        InvestorAssetEntity  asset = investorAssetDao.queryObject(id);
        investorAssetDao.delete(id);
        investorAcctDao.changeAmt(asset.getUserId(),0-asset.getAmount().doubleValue());
    }


    @Override
    public List<InvestorAssetEntity> queryLimit(Integer offset, Integer num){
        return investorAssetDao.queryLimit(offset,num);
    }

}
